<template>
  <div class="yygh_bg">
    <div class="hd mt10">
      <img src="../../assets/yygh.png" />
    </div>
    <search-bar></search-bar>
    <position>
      <router-link to="/yygh">预约挂号</router-link>
      &gt;
      <span class="last">预约挂号</span>
    </position>
    
    <steps :step="0"></steps>

    <div class="yybox four-cornor-wrapper">
      <i class="l"></i>
      <i class="r"></i>
      <i class="t"></i>
      <i class="b"></i>
      <div class="yycontent">
        <div class="yycontent_title">科室查找</div>
        <div class="select_tab">
          <!-- <div class="recent">
            <ul>
              <li class="origin">最近就诊的医生：</li>
              <li>周仲元</li>
            </ul>
            <div class="clear">
              × 清空
            </div>
          </div> -->
          <div class="yyzs">
            <div class="appbb_body">
              <div id="keshilist" class="appbb_content">
                
                <div class="appbb_keshi_box" v-for="item in departments" :key="item.id">
                  <div>
                    <div class="appbb_keshi_title">
                      {{item.categoryText}}
                    </div>
                    <div class="appbb_keshi_list">
                      <div :class="['appbb_keshi_item', dept.isActive ? 'active': '']" :key="dept.deptId" @click="getDoctors(item, dept)" v-for="dept in item.deptInfos">
                        <a href="javascript:;">{{dept.deptName}}</a>
                      </div>
                    </div>
                  </div>
                  <div class="group_line2"></div>
                </div>
  
              </div>
            </div>
          </div>
        </div>
        <div class="doctor-wrapper" v-if="doctors.length > 0" style="min-height:200px;">
          
          <div class="doctor_tab" v-for="(doctor, index) in doctors" :key="doctor.localDoctorId">
            <div class="doctor_inform">
              <div class="avatar" @click="goDoctor(doctor)">
                <img class="doctor-image" :alt="doctor.doctorName" v-lazy="DOCTOR_AVATAR+doctor.localDoctorId+'.jpg'"/>
              </div>
              <div class="desc">
                <p class="name">{{doctor.doctorName || doctor.regDeptName}}</p>
                <p class="title">{{DOCTOR_LEVEL[doctor.doctorLevel] || '暂无'}}</p>
                <p class="area">{{doctor.speciality || ''}}</p>
                <p class="click_detail" v-show="doctor.doctorName">
                  <a href="javascript:;"  @click="goDoctor(doctor)">点击查看详情&gt;</a>
                </p>
              </div>
            </div>
            <div class="doctor_schedule">
              <ul>
                <li class="backward">
                  <div title="上一周" :class="['form_title', doctor.prevPage ? 'active_arrow': '']" @click="prevPage(index, doctor)"></div>
                  <div class="morning">上午</div>
                  <div class="noon">下午</div>
                </li>
                <div class="list-wrapper">
                  <div class="list-scroller" :id="'listScroller'+index">
                  <li class="single_day" v-for="(day, i) in days" :key="day.orderDate1">
                    <div class="form_title">
                      {{day.orderDate1}}
                      <br/>
                      {{day.orderWeek2}}
                    </div>
                    <div class="morning" v-html="doctor.doctorDays[i].morning" @click="appointClickMorning(doctor.doctorDays[i], doctor, day)"></div>
                    <div class="noon" v-html="doctor.doctorDays[i].noon" @click="appointClickNoon(doctor.doctorDays[i], doctor, day)"></div>
                  </li>
                  </div>
                </div>
                <li class="forward">
                  <div title="下一周" :class="['form_title', doctor.nextPage ? 'active_arrow': '']" @click="nextPage(index, doctor)"></div>
                  <div class="morning"></div>
                  <div class="noon"></div>
                </li>
              </ul>
            </div>
          </div>
        </div>
  
        <div class="no-data" v-else>
          {{noDataMessage}}
        </div>
      </div>
  
    </div>
    <!-- 用户须知 第一次访问弹出 -->
    <div class="mask" v-if="mask_shown">
      <div class="alert_box four-cornor-wrapper">
        <i class="l"></i>
        <i class="r"></i>
        <i class="t"></i>
        <i class="b"></i>
        <div class="box_title">
          <span>用户须知</span>
        </div>
        <b class="clost_btn" v-on:click="mask_shown = false"></b>
        <div class="msg_content">
          <p v-for="msg in msg_content" v-bind:class="msg.class" :key="msg.class">{{msg.content}}</p>
        </div>
        <div class="center">
          <a href="javascript:;" class="common-main-button" @click="argeeHandle">我已知晓</a>
        </div>
      </div>
    </div>
  
    <el-dialog :visible.sync="dialogShow" custom-class="dialog-common">
      
      <div class="dialog-title" slot="title">
        请选择就诊时段 <small class="t1">{{dialogTitle}}</small>
      </div>
      <div class="select-time">
        <div class="time-box" v-for="time in times" :key="time.startTime">
          <a href="javascript:;" v-if="time.availableCount > 0" @click="timeClick(time)" :class="['sprites',time.isActive ? 'active' : '']">{{time.startTime}} - {{time.endTime}}</a>
          <a href="javascript:;" :class="['sprites','disable']" v-else>{{time.startTime}} - {{time.endTime}}</a>
        </div>
      </div>
      <div class="center" slot="footer">
        <a href="javascript:;" class="common-main-button"  @click="confirmHandle">确定</a>
						<a href="javascript:;"  class="common-sub-button" @click="dialogShow=false">取消</a>						
      </div>
    </el-dialog>
  
  </div>
</template>

<script>
import {
  commonAjax,
  ORG_ID,
  PLATFORM_PREFIX,
  DOCTOR_LEVEL,
  APPOINT_TIPS,
  DOCTOR_AVATAR
} from '../../api/api'
import Steps from '../../components/Steps'
import Position from '../../components/Position'
import SearchBar from '../../components/SearchBar'

export default {
  components: {Steps, Position, SearchBar},
  data() {
    return {
      departments: [],
      days: [],
      doctors: [],
      times: [],
      DOCTOR_LEVEL: DOCTOR_LEVEL,
      mask_shown: false,
      dialogShow: false,
      dialogTitle: '',
      msg_content: [],
      noDataMessage: '暂无数据',
      DOCTOR_AVATAR: DOCTOR_AVATAR,
      isMorning: true
    }
  },
  mounted() {
    if (!localStorage.accessToken) {
      return
    }
    if (!localStorage.person) {
      setTimeout(() => this.$router.push('/personal?from=login'), 400)
    }
    // 获取科室
    this.$store.commit('UPDATE_LOADING')
    commonAjax([ORG_ID], `${PLATFORM_PREFIX}.deptService`, 'findCategoryAndDept').then(res => {
      this.$store.commit('UPDATE_LOADING')
      if (res.data.code === 200) {
        this.departments = res.data.body || []
        this.resetActive()
      } else {
        this.$message({
          message: res.data.msg,
          type: 'error'
        })
      }
    }).catch(res => {
      this.$store.commit('UPDATE_LOADING')
      localStorage.removeItem('accessToken')
      this.$message({
        message: '登录失效，请重新登录',
        type: 'error'
      })
    })
    // 获取排版周期
    commonAjax(
      [ORG_ID, '', ''],
      `${PLATFORM_PREFIX}.registrationService`,
      'getTimePeriod'
    ).then(res => {
      if (res.data.code === 200) {
        this.days = res.data.body
      } else {
        this.$message({
          message: res.data.msg,
          type: 'error'
        })
      }
    }).catch(res => console.warn(res))
  },
  methods: {
    appointClickMorning(doctorDays, doctor, day) {
      this.isMorning = true
      if (!doctorDays.morningActive) {
        return false
      }
      this.saveInfo(doctorDays, doctor, day)
    },
    appointClickNoon(doctorDays, doctor, day) {
      this.isMorning = false
      if (!doctorDays.noonActive) {
        return false
      }
      this.saveInfo(doctorDays, doctor, day)
    },
    goDoctor (doctor) {
      if (!doctor.doctorName) {
        return false
      }
      // localStorage.doctor = JSON.stringify(doctor)
      this.$router.push({
        path: '/yygh/doctor',
        query: {
          localDeptId: doctor.localDeptId,
          localDoctorId: doctor.localDoctorId
        }
      })
    },
    saveInfo(doctorDays, doctor, day) {
      if (this.isMorning) {
        localStorage.dep = JSON.stringify(doctorDays.morningDepInfo)
      } else {
        localStorage.dep = JSON.stringify(doctorDays.noonDepInfo)
      }
      localStorage.day = JSON.stringify(day)
      localStorage.doctor = JSON.stringify(doctor)
      if (localStorage.firstcome === '1') {
        this.argeeHandle()
      } else {
        localStorage.firstcome = '1'
        this.showDialog()
      }
    },
    timeClick(time) {
      this.times.forEach(v => v.isActive = false)
      time.isActive = true
      localStorage.time = JSON.stringify(time)
    },
    showDialog() {
      this.mask_shown = true
      this.msg_content = APPOINT_TIPS
    },
    argeeHandle() {
      let dep = JSON.parse(localStorage.dep)
      let day = JSON.parse(localStorage.day)
      let doctor = JSON.parse(localStorage.doctor)
      // 获取号源时间段
      this.mask_shown = false
      this.$store.commit('UPDATE_LOADING')
      commonAjax(
        [ORG_ID, doctor.localRegDeptId, doctor.localDoctorId || '', dep.workDate, dep.seqId],
        `${PLATFORM_PREFIX}.registrationService`,
        'getDocAndDeptSouce'
      ).then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 200 && res.data.body.length > 0) {
          this.dialogTitle = `（科室：${doctor.regDeptName} —— 时间：${day.orderDate}）`
          this.dialogShow = true
          let d = res.data.body
          d.forEach(v => v.isActive = false)
          this.times = d
        } else {
          this.$message({
            message: '抱歉，该医生的号源已经预约完',
            type: 'error'
          })
        }
      }).catch(res => {
        this.$message({
          message: res,
          type: 'error'
        })
      })
    },
    confirmHandle() {
      let isSelect = this.times.some(time => time.isActive === true)
      if (isSelect) {
        this.$router.push('/yygh/confirm')
      } else {
        return false
      }
    },
    resetActive() {
      this.departments.forEach(item => {
        item.deptInfos.forEach(dept => {
          dept.isActive = false
        })
      })
    },
    getDoctors(item, dept) {
      let _this = this
      this.doctors = []
      this.resetActive()
      dept.isActive = true
      // 获取医生列表
      localStorage.dept = JSON.stringify(dept)
      this.$store.commit('UPDATE_LOADING')
      commonAjax(
        [ORG_ID, '', dept.localDeptId, dept.deptId], `${PLATFORM_PREFIX}.registrationService`,
        'getDoctorDeptListPc'
      ).then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 200) {
          // console.log(res.data)
          res.data.body.forEach(v => {
            let temp = []
            v.prevPage = false
            v.nextPage = true
            this.days.forEach(a => {
              temp.push({
                morning: '',
                noon: '',
                morningActive: false,
                noonActive: false,
                morningDepInfo: '',
                noonDepInfo: ''
              })
            })
            v.doctorDays = temp
          })
          this.doctors = res.data.body || []
          this.days.forEach((day, index) => {
            this.doctors.forEach(doc => {
              let depDocPlanPcs = doc.depDocPlanPcs
              if (Array.isArray(depDocPlanPcs)) {
                depDocPlanPcs.forEach(dep => {
                  _this.getSameDay(day, index, doc, dep)
                })
              }
            })
          })
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          })
        }
      }).catch(res => {
        this.$store.commit('UPDATE_LOADING')
      })
    },
    getSameDay(day, index, doc, dep) {
      let _this = this
      if (dep.workDate === day.orderDate) {
        if (dep.planTime === '1') {
           doc.doctorDays[index].morningDepInfo = dep
          if (dep.stopFlag === '1') {
            doc.doctorDays[index].morning = '<div class="book_state_5">已停诊</div>'
          } else if (dep.status === '2') {
            doc.doctorDays[index].morning = '<div class="book_state_4">已约满</div>'
          } else {
            doc.doctorDays[index].morning = '<div class="book_state_1">可预约</div>'
            doc.doctorDays[index].morningActive = true
          }
        } else {
           doc.doctorDays[index].noonDepInfo = dep
          if (dep.stopFlag === '1') {
            doc.doctorDays[index].noon = '<div class="book_state_5">已停诊</div>'
          } else if (dep.status === '2') {
            doc.doctorDays[index].noon = '<div class="book_state_4">已约满</div>'
          } else {
            doc.doctorDays[index].noon = '<div class="book_state_1">可预约</div>'
            doc.doctorDays[index].noonActive = true
          }
        }
      }
    },
    nextPage (index, doctor) {
      if (!doctor.nextPage) {
        return false
      }
      document.getElementById('listScroller'+index).style.transform = 'translate3d(-50%, 0, 0)'
      doctor.nextPage = !doctor.nextPage
      doctor.prevPage = !doctor.prevPage
    },
    prevPage (index, doctor) {
      if (!doctor.prevPage) {
        return false
      }
      document.getElementById('listScroller'+index).style.transform = 'translate3d(0, 0, 0)'
      doctor.nextPage = !doctor.nextPage
      doctor.prevPage = !doctor.prevPage
    }
  }
}
</script>

<style lang="less">
@import '../../common/css/vars.less';

.doctor_tab li {
  float: left;
}

.appbb_keshi_box {
  position: relative;
  margin-top: 20px;
}

.appbb_keshi_title {
  display: inline-block;
  position: absolute;
  width: 120px;
  text-align: center;
  top: 0;
  left: 0;
  line-height: 26px;
}

.appbb_keshi_title:after {
  content: '';
  height: 20px;
  width: 2px;
  background: #cb9990;
  display: block;
  position: absolute;
  top: 5px;
  right: -2px;
}

.appbb_body .appbb_content .appbb_keshi_list {
  display: inline-block;
  width: 850px;
  margin-left: 150px;
}

.appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item {
  display: inline-block;
  margin-right: 1px;
  vertical-align: top;
  font-size: 14px;
  padding: 1px;
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 4px;
  line-height: 20px;
  margin-bottom: 5px;
}

.appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item.active {
  background: none 0% 0% repeat scroll rgb(238, 113, 0);
}

.appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item.active a {
  color: #fff;
}

.appbb_body .appbb_content .appbb_keshi_list .appbb_keshi_item a {
  display: inline-block;
  padding: 2px;
  color: #333;
  &:hover {
    color: @color-primary;
  }
}

.yybox {
  width: 1080px;
  margin: auto;
  background: #fff;
}

.side {
  width: 1080px;
  height: 27px;
  background: url('../../assets/box_side.jpg') 0 0 no-repeat;
  background-size: 100% 100%;
}

.side_up {
  transform: rotate(180deg);
}

.yycontent {
  width: 1080px;
}

.select_tab {
  border: 1px solid #f8e6e2;
  width: 1050px;
  margin: auto;
  margin-top: 20px;
  background: #FFFBF8;
  padding: 10px;
}

.yycontent_title {
  padding: 20px 40px 0;
  font-size: 24px;
  color: #EE7100;
}

.recent {
  padding: 10px 0 20px;
  border-bottom: 1px solid #f8e6e2;
}

.recent ul,
.recent li {
  display: inline-block;
}

.recent li {
  margin: 0 20px;
  cursor: pointer;
}

.recent li.origin {
  color: #666;
  cursor: default;
}

.recent .clear {
  float: right;
  margin-right: 20px;
  color: #999;
  cursor: pointer;
}

.doctor_tab {

  width: 1050px;
  margin: 10px auto 0;
  overflow: hidden;
}

.doctor_tab:nth-child(3) {
  margin-top: 20px;
}

.doctor_inform {
  overflow: hidden;
  border: 1px solid #f8e6e2;
  border-right: 0;
  width: 310px;
  float: left;
  background: #FFFBF8;
}



.doctor_inform {
  .avatar {
    float: left;
    margin: 10px;
    position: relative;
    height: 128px;
    cursor: pointer;
  }
  .desc {
    margin: 10px 10px 10px 120px;
    position: relative;
    height: 128px;
  }
  .name {
    color: #a4381e;
    font-weight: bold;
    margin-bottom: 8px;
  }
}

.area {
  color: #999;
  overflow: hidden;
  height: 3.6em;
}

.click_detail {
  position: absolute;
  bottom: 0;
  cursor: pointer;
  margin-bottom: 0;
  line-height: 1;
  width: 120px;
}
.doctor-image {
  width: 100px;
  height: 126px;
  border: none;
}
</style>